<template>
  <component :is="tag">
    <a-menu
      :mode="menuMode"
      :theme="theme"
      :accordion="true"
      :auto-open-selected="true"
      :collapsed="menuMode === 'horizontal' ? false : appStore.isCollapse"
      v-model:selectedKeys="defaultPath"
      v-model:openKeys="defaultExpandKeys"
      @menu-item-click="onMenuClick"
      v-bind="menuProps"
    >
      <template v-for="(item, index) of menuOptions" :key="item.key">
        <template v-if="!item.children">
          <a-menu-item :key="item.key">
            {{ item.label }}
          </a-menu-item>
        </template>
        <template v-else>
          <SubMenu :key="item.key" :menu-info="item" />
        </template>
      </template>
    </a-menu>
  </component>
</template>

<script lang="ts">
  import {
    computed,
    defineComponent,
    nextTick,
    onMounted,
    PropType,
    reactive,
    ref,
    shallowReactive,
    watch,
    watchEffect,
  } from 'vue'
  import { RouteRecordRaw, useRoute, useRouter } from 'vue-router'
  import { isExternal } from '@/utils'
  import useAppConfigStore from '@/store/modules/app-config'
  import { LayoutMode, SideTheme, ThemeMode } from '@/store/types'
  import { transfromMenu } from '@/store/help'
  import useCommonStore from '@/store/modules/common'
  import layoutMode from '@/setting/index'

  export default defineComponent({
    name: 'ScrollerMenu',
    props: {
      routes: {
        type: Array as PropType<Array<RouteRecordRaw>>,
        require: true,
        default: () => [],
      },
      mode: {
        type: String as PropType<'vertical' | 'pop' | 'horizontal' | 'popButton' | undefined>,
        default: 'vertical',
      },
      menuProps: {
        type: Object,
        default: () => ({}),
      },
    },
    emits: ['top-item-click'],
    setup(props, { emit }) {
      const useCommon = useCommonStore()
      const appStore = useAppConfigStore()
      const menuOptions = shallowReactive<any[]>([])
      const defaultPath = ref<string[]>([])
      const defaultExpandKeys = ref<string[]>([])
      const menuMode = computed(() => props.mode)
      const currentRoute = useRoute()
      const router = useRouter()
      defaultPath.value.push(
        menuMode.value === 'vertical' ? currentRoute.fullPath : currentRoute.matched[0].path
      )
      const tag = ref(menuMode.value === 'vertical' ? 'Scrollbar' : 'div')
      const widthNum = ref(menuMode.value === 'vertical' ? '142px' : '250px')

      const theme = computed(() => {
        if (appStore.theme === ThemeMode.DARK) {
          return 'dark'
        }
        if (appStore.layoutMode === LayoutMode.TTB) {
          return 'light'
        }
        return appStore.sideTheme === SideTheme.IMAGE
          ? 'dark'
          : appStore.sideTheme === SideTheme.WHITE
          ? 'light'
          : 'dark'
      })
      handleExpandPath()

      function handleMenu(routes?: Array<RouteRecordRaw>) {
        console.log('csa', defaultPath.value)
        menuOptions.length = 0
        const tempMenus = transfromMenu(routes || [])
        let aa = ref('')
        let aas = ref('')
        let aList: any = []
        let newLists: any = []
        menuOptions.push(...tempMenus)
        menuOptions.forEach((item, index) => {
          if (index == 0) {
            aa.value = item.name
            aas.value = item.key
            if (localStorage.getItem('return')) {
              const asx: any = localStorage.getItem('return')
              aList = JSON.parse(asx)

              if (aList.length == 6) {
                aList.shift()
              }
              const item = aList.find((i) => i.key === aas.value)
              console.log('查看', item)
              if (!item) {
                const items = findMenuOption(menuOptions, aas.value)
                if (items) {
                  aList.unshift(items)
                  localStorage.removeItem('return')
                  localStorage.setItem('return', JSON.stringify(aList))
                }
              } else {
                newLists = aList.filter((i) => i !== item)
                newLists.unshift(item)
                localStorage.removeItem('return')
                localStorage.setItem('return', JSON.stringify(newLists))
              }
            } else {
              aList.push(item)
              localStorage.removeItem('return')
              localStorage.setItem('return', JSON.stringify(aList))
            }
          }
        })

        // add(aas.value)
        useCommon.titleName(aa.value)
      }
      function handleExpandPath() {
        const paths = currentRoute.fullPath.split('/')
        defaultExpandKeys.value = []
        const resultPaths = paths
          .filter((it) => !!it)
          .reduce(
            (pre, cur) => {
              pre.push(pre.slice(pre.length - 1, pre.length) + '/' + cur)
              return pre
            },
            ['']
          )
        resultPaths.forEach((it) => {
          if (it && !defaultExpandKeys.value.includes(it)) {
            defaultExpandKeys.value.push(it)
          }
        })
      }
      function findMenuOption(menuOptions, key) {
        for (let item of menuOptions) {
          if (item.key === key) {
            return item
          } else if (item.children) {
            const foundItem: any = findMenuOption(item.children, key)

            if (foundItem) {
              return foundItem
            }
          }
        }

        return null
      }

      function add(key: any) {
        let list: any = []
        let newList: any = []
        console.log('看看是啥玩意', key)
        if (localStorage.getItem('return')) {
          const aas: any = localStorage.getItem('return')
          list = JSON.parse(aas)
          if (layoutMode.layoutMode == 'ltr') {
            if (list.length == 6) {
              list.shift()
            }
            const item = list.find((i) => i.key === key)
            console.log('查看', item)
            if (!item) {
              const items = findMenuOption(menuOptions, key)
              if (items) {
                list.unshift(items)
                localStorage.removeItem('return')
                localStorage.setItem('return', JSON.stringify(list))
              }
            } else {
              newList = list.filter((i) => i !== item)
              newList.unshift(item)
              localStorage.removeItem('return')
              localStorage.setItem('return', JSON.stringify(newList))
            }
          } else {
            if (list.length == 6) {
              list.shift()
            }
            const item = list.find((i) => i.key === key)
            console.log('查看', item)
            if (!item) {
              const items = menuOptions.find((i) => i.key === key)
              if (items) {
                list.unshift(items)
                localStorage.removeItem('return')
                localStorage.setItem('return', JSON.stringify(list))
              }
            } else {
              newList = list.filter((i) => i !== item)
              newList.unshift(item)
              localStorage.removeItem('return')
              localStorage.setItem('return', JSON.stringify(newList))
            }
          }
        } else {
          const items = menuOptions.find((i) => i.key === key)
          if (items) {
            list.unshift(items)
            localStorage.removeItem('return')
            localStorage.setItem('return', JSON.stringify(list))
          }
        }
      }

      function onMenuClick(key: string) {
        console.log('ceshi ', key)
        console.log('试试', menuMode.value)
        add(key)
        // return false
        if (menuMode.value === 'horizontal') {
          emit('top-item-click', key)
          return
        }
        if (isExternal(key)) {
          window.open(key)
        } else {
          router.push(key)
          if (appStore.deviceType === 'mobile') {
            console.log('111')
            appStore.toggleCollapse(true)
          }
        }
      }

      watch(
        () => currentRoute.fullPath,
        (newVal) => {
          console.log(newVal, '142424214')
          defaultPath.value.length = 0
          defaultPath.value.push(
            menuMode.value === 'vertical' ? newVal : currentRoute.matched[0].path
          )
          if (newVal.includes('?card')) {
            defaultPath.value.push(newVal.substring(0, newVal.lastIndexOf('?')))
          }

          handleExpandPath()
        }
      )
      watch(
        () => props.mode,
        (newVal) => {
          newVal === 'vertical' ? 'Scrollbar' : 'div'
        }
      )
      watchEffect(() => {
        handleMenu(props.routes)
      })
      const state = reactive({
        text: 'center',
        padding: '0',
      })

      onMounted(() => {
        nextTick(() => {
          const items = document.querySelectorAll(
            '.arco-trigger-popup.arco-trigger-position-bl.arco-menu-pop-trigger'
          )
          items.forEach((it) => {
            it.setAttribute('style', 'width: 150px')
          })
        })
        if (appStore.layoutMode === 'ltr') {
          state.text = 'left'
          state.padding = '15px'
        }
      })
      return {
        state,
        widthNum,
        appStore,
        tag,
        theme,
        menuMode,
        defaultPath,
        defaultExpandKeys,
        menuOptions,
        onMenuClick,
      }
    },
  })
</script>
<style></style>

<style lang="less" scoped>
  // :deep(.arco-menu) {
  //   width: 120px;
  // }
  #nprogress {
    z-index: 9999;
  }
  :deep(.arco-menu-vertical .arco-menu-inner) {
    padding: 0;
    // padding-top: 3px;
    width: v-bind('widthNum.value');
    height: calc(100vh - 57px);
    z-index: -1;
    border-right: 1px solid #e5e6eb;
    border-top: 1px solid #e5e6eb;
    box-sizing: border-box;
  }
  :deep(.arco-menu-vertical .arco-menu-item) {
    width: v-bind('widthNum.value');
    height: 44px;
  }
  :deep(.arco-menu-item:hover) {
    width: v-bind('widthNum.value');
    background-color: #e5e6eb;
    // border-radius: 5px;
  }
  :deep(.arco-menu-light .arco-menu-item.arco-menu-selected) {
    width: v-bind('widthNum.value');
    background-color: #e8f7ff;
    // border-radius: 5px;
  }
  :deep(.arco-menu-dark .arco-menu-item.arco-menu-selected) {
    width: v-bind('widthNum.value');
    background-color: black;
    // border-radius: 5px;
  }
  :deep(.arco-menu-dark .arco-menu-item) {
    width: v-bind('widthNum.value');
    color: #ffff;
    background-color: black;
  }

  :deep(.arco-menu-dark .arco-menu-inline-header) {
    background-color: black;
  }

  :deep(.arco-menu-dark) {
    background-color: black;
  }

  :deep(
      .arco-menu-vertical .arco-menu-item,
      .arco-menu-vertical .arco-menu-group-title,
      .arco-menu-vertical .arco-menu-pop-header,
      .arco-menu-vertical .arco-menu-inline-header
    ) {
    text-align: v-bind('state.text');
    font-size: 15px;
    padding-left: v-bind('state.padding');
    padding-right: 0;
    line-height: 44px;
  }

  :deep(
      .arco-menu-vertical .arco-menu-item,
      .arco-menu-vertical .arco-menu-group-title,
      .arco-menu-vertical .arco-menu-pop-header,
      .arco-menu-vertical .arco-menu-inline-header
    ) {
    margin-bottom: 0;
  }

  :deep(.arco-menu-collapsed) {
    margin: 0 auto;
  }
  :deep(.arco-menu-vertical .arco-menu-item) {
    max-height: 44px;
  }
  .scrollbar {
    height: calc(100vh - 57px) !important;

    overflow-y: auto;
    &::-webkit-scrollbar {
      width: 0;
    }
  }
</style>
